package com.ff.sca.common.filter;

import com.alibaba.fastjson.JSONObject;
import com.ff.sca.admin.service.RedisService;
import com.ff.sca.common.codeenum.CodeEnum;
import com.ff.sca.common.entity.resmsg.ResMsg;
import com.ff.sca.common.util.CharUtil;
import com.ff.sca.common.util.IpUtil;
import com.ff.sca.common.util.JWT;
import com.ff.sca.suser.entity.ScaSysUser;
import com.ff.sca.suser.service.IScaSysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * token拦截器
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private IScaSysUserService sysUserService;
    @Autowired
    RedisService redisService;

    /**
     * token验证拦截器
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userIp = IpUtil.getIpAddr(request);
        String redisToeken = redisService.getAppCache("manager_token_" + userIp);
        if (CharUtil.isNotEmpty(redisToeken)) {
            redisService.putAppCache("manager_token_" + userIp, redisToeken, 15, TimeUnit.MINUTES);
        }
        //token验证
        response.setCharacterEncoding("utf-8");
        String token = request.getParameter("token");
        String userId = request.getParameter("tokenUserId");
        JSONObject error = new JSONObject();
        if (CharUtil.isNotEmpty(token) && CharUtil.isNotEmpty(userId)) {
            ScaSysUser user = JWT.unsign(token, ScaSysUser.class);
            ScaSysUser muser = sysUserService.selectById(userId);
            if (muser != null && user != null && user.getId().equals(muser.getId())
                    && user.getUserName().equals(muser.getUserName())
                    && user.getLoginPwd().equals(muser.getLoginPwd())) {
                return true;
            } else {//token过期
                redisService.delCache("manager_token_" + userIp);
                ResMsg res = new ResMsg(CodeEnum.TOKEN_801.getCode(), CodeEnum.TOKEN_801.getMsg(), "");
                responseMessage(response, response.getWriter(), res);
                return false;
            }
        } else {//token,userId请求参数不合法
            ResMsg res = new ResMsg(CodeEnum.HTTP_199.getCode(), CodeEnum.HTTP_199.getMsg(), "");
            responseMessage(response, response.getWriter(), res);
            return false;
        }
    }

    //请求不通过，返回错误信息给客户端
    private void responseMessage(HttpServletResponse response, PrintWriter out, ResMsg res) {
        response.setContentType("application/json; charset=utf-8");
        String json = JSONObject.toJSONString(res);
        out.print(json);
        out.flush();
        out.close();
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception arg3) throws Exception {

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView model) throws Exception {

    }
}
